import {//二手交易
  Button,
  Col,
  Upload,
  Input,
  Drawer,
  Space,
  Form,
  Row,
  Select,
  Modal,
  InputNumber,
  Checkbox,
  message,
  Pagination,
  Table,
} from 'antd';
import React, { useState, useEffect } from 'react';
import {
  DoubleRightOutlined,
  PlusOutlined,
  DollarOutlined,FileDoneOutlined
} from '@ant-design/icons';
import { StudentInfo } from '../../../utils/model';
import { postGoods, getSchoolList,getGoodsList,getChanging,getHistory } from '@/api/index';
import CommodityCard from '../SecondhandTransfer/components/CommodityCard'
import GoodDetailModal from './components/GoodDetailModal';
import { formatDate } from '../../../utils/tool';
import './index.css';
const {Consumer} = StudentInfo
const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = (error) => reject(error);
  });
const { Option } = Select;

export default function SecondhandTransfer(props) {
  const [changeValue, setChangeValue] = useState(false)//切换显示筛选按钮
  const [maxlenght, setMaxlenght] = useState()//价格上限
  const [minlenght, setMinlenght] = useState()//价格下限
  const [knife, setKnife] = useState()//是否小刀
  const [schoolName, setschoolName] = useState()//校区
  const [keyCode, setkeyCode] = useState()//商品筛选关键字
  const [schoolSect, setschoolSect] = useState([])//校区列表
  const [goodsList, setGoodsList] = useState([])//商品列表
  const [visible, setVisible] = useState(false);//发布商品
  const [params, setParams] = useState({});
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [itemData, setitemData] = useState();
  const [deatilModalVisible,setDetailModalVisible] = useState(false); //商品详情弹窗
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [fileList, setFileList] = useState([]);
  const [number, setNumber] = useState();//判断交易中的数量
  const [mainfileList, setMainFileList] = useState([]);
  const [historylist, setHistorylist] = useState(0);//切换历史记录
  const [buttonColor, setButtonColor] = useState(2);//按钮切换颜色
  const [DataSourceTable, setDataSourceTable] = useState([]);//交易记录的保存
  // 是否显示筛选条件
  const [isShow, setIsShow] = useState(false);
  const columns = [
    {
      title: '卖家ID',
      dataIndex: 'publisherId',
      key: 'publisherId',
      align: 'center',
    },
    {
      title: '商品编号',
      dataIndex: 'goodId',
      key: 'goodId',
      align: 'center',
      render:(id,record)=>{
       
        return <li className='MoneyStyleTwo'
        //  onClick={()=>{
        //   setDetailModalVisible(true);setitemData(record)
        // }}
        >{id}
      </li>
      
      
    }
    },
    {
      title: '申购金额',
      dataIndex: 'offer',
      key: 'offer',
      align: 'center',
      render:(id,record)=>{
       
          return <li className='MoneyStyleOne'>{id}元</li>
        
        
      }
    },
    {
      title: '申购时间',
      dataIndex: 'offerTime',
      key: 'offerTime',
      align: 'center',
      render:(id)=>{
        return (<div>{formatDate(id)}</div>)
      }
    },
    {
      title: '买家ID',
      dataIndex: 'orderId',
      key: 'orderId',
      align: 'center',
    },
    {
      title: '买家昵称',
      dataIndex: 'orderName',
      key: 'orderName',
      align: 'center',
    },
    {
      title: '申购留言',
      dataIndex: 'message',
      key: 'message',
      align: 'center',
    },
    {
      title: '最终成交额',
      dataIndex: 'finalAmount',
      key: 'finalAmount',
      align: 'center',
      render:(id,record)=>{
       
        return <li className='MoneyStyleOne'>{id}元</li>
      
      
    }
    },
    {
      title: '交易完成时间',
      dataIndex: 'reachTime',
      key: 'reachTime',
      align: 'center',
      render:(id)=>{
        return (<div>{formatDate(id)}</div>)
      }
    },
    {
      title: '交易类型',
      dataIndex: 'mineGood',
      key: 'mineGood',
      align: 'center',
      render:(id,record)=>{
        if(!id)
        {
          return <li className='lineStyle'><span className='diansytle0'></span> 我买到的</li>
        }
        else
        {
          return <li className='lineStyle'><span className='diansytle3' ></span> 我卖出的</li>
        }
        
      }
    },
  ];
  const onChangePage = async(page) => {
    console.log(page);
    console.log(111)
    setCurrent(page);
  };
  const layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 24,
    },
  };

  
  useEffect(() => {
    console.log('effect进入的');
     getGoodsDate(params)
  }, [current]);
  useEffect(() => {
     getSchoolDate()
  }, []);
  const [form] = Form.useForm();
  const handleChange = (value) => {
    setParams(()=>{params.knife = value
      return params
    })
    setKnife(value)
  };
  //获取校区列表
  const getSchoolDate = async () => {
    const res = await getSchoolList()
    setschoolSect(res.data?.campus)
  }

  //获取交易中的列表
  const getChangingDate = async () => {
      const res = await getChanging()
    setGoodsList(res?.data?.data);
    setNumber(res?.data?.data.length)
    setTotal(res?.data?.total)
  }
  
  // 获取商品列表
  const getGoodsDate = async (params) => {
    if(params){
      const res = await getGoodsList({
           keyword:params?.keyCode,
      campus:params?.schoolName,
      lowPrice:params?.knife,
      minPrice:params?.minlenght,
      maxPrice:params?.maxlenght,
      pageSize:10,
      pageNum:current
    })

    setGoodsList(res?.data?.data);
    setTotal(res?.data?.pagination?.total)
    }
     else{

      const res = await getGoodsList({
      pageSize:10,
      pageNum:current})
      setGoodsList(res.data.data);
      setTotal(res.data.pagination.total)
     }
     const data = await getChanging()
     setNumber(data?.data?.data.length)
  }
   //获取交易列表
   const getHistoryList = async () => {
    
    const res = await getHistory()
    if(res.data.code=='200')
    {
      setDataSourceTable(res.data.data)
    }
    
  }
  //发布商品的保存
  const postGoodsDate = async () => {
    // debugger
    let url ='';
     fileList.map((item) => {
      url =url+ item.response + ','
    })
    const res = await postGoods({
      anonymous:form.getFieldValue('anonymous'),
      goodName:form.getFieldValue('Name'),
      goodDetail:form.getFieldValue('goodDetail'),
      price:form.getFieldValue('price'),
      originalPrice:form.getFieldValue('originalPrice'),
      lowPrice:form.getFieldValue('bigDeal'),
      pictureList:url,
      mainPicture:mainfileList[0].response,
      campus:form.getFieldValue('campus'),
    })
    if(res.data.code=='200')
    {
      form.resetFields()
      setschoolSect(res.data.campus)
      setVisible(false)
      getGoodsDate()
      getSchoolDate()
      setFileList([])
      setMainFileList([])
      message.success('发布成功!')
    }
    
  }
  const onClose = () => {
    setVisible(false);
  };
  const resetDate=async() => {
    setParams(
      {
        schoolName:'',
        minlenght:'',
        maxlenght:'',
        keyCode:'',
        knife:''
      }
     
    );
     setKnife('');
     setschoolName('');
     setMaxlenght('');
     setMinlenght('');
     setkeyCode('')
     getGoodsDate()
  }

//筛选函数
  const getFilter = async() => {
    // setGoodsList('')
    if(params.maxlenght == 0){
      // message.error('价格区间上限不能为0哦～')
      // return
    }
     if(params.minlenght || params.maxlenght){
      if(params.minlenght&&params.maxlenght){
        console.log('筛选进入的');
        getGoodsDate(params)
        setChangeValue(false);
      }
      else
      {
         message.error('请把价格区间补充全～')
      return
      }
     }
     else
     {
      console.log('筛选进入的');
        getGoodsDate(params)
        setChangeValue(false);
     }
  };


  const handleCancel = () => setPreviewVisible(false);

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };

  const handleChangephoto = ({ fileList: newFileList }) =>{setFileList(newFileList)}//细节图
  const handleChangemainphoto = ({ fileList: newFileList }) => {setMainFileList(newFileList)}//主图
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <>
      <GoodDetailModal visible={deatilModalVisible} getCenterList={getChangingDate} getGoodsList={getGoodsDate}  Detail={itemData}  setVisible={(e)=>setDetailModalVisible(e)}></GoodDetailModal>
      <div style={{ height: '1000px' }}>
      <div className='topFixBox'>
      {changeValue ?
        <div className='screenBox'>
          <div style={{ alignItems: 'center', display: 'flex', width: '100%' }}>
            <div style={{ display: 'flex', marginTop: '10px' }}>
              <span
                style={{ height: '30px', lineHeight: '33px', color: '#4095E5' }}
              >
                校区：
              </span>
              <div style={{ width: '300px', height: '40px', marginRight: '30px' }}>
                <Select
                  allowClear
                  value={schoolName}
                  style={{
                    width: 240,
                    borderRadius: '5px'
                  }}
                  onChange={(e)=>{
                    setschoolName(e)
                    setParams(()=>{params.schoolName = e
                      return params
                    })
                  }}
                >
                  {schoolSect?.map((item, index) => {
                    return <Option value={item.campusName}>{item.campusName}</Option>
                  })
                  }
                </Select>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
              <span
                style={{ height: '30px', lineHeight: '33px', color: '#4095E5' }}
              >
                价格区间：
              </span>
              <div style={{ width: '80px', marginRight: '11px' }}>
                <InputNumber
                  //  type="password"
                  value={minlenght}
                  onChange={(e) => {
                    setMinlenght(e)
                    setParams(()=>{
                      params.minlenght = e
                      return params
                    })
                  }}
                  max={maxlenght}
                  min={0}

                />
              </div> 元
              ~ <div style={{ width: '80px', marginRight: '11px' }}>
                <InputNumber
                  type="number"
                  value={maxlenght}
                  onChange={(e) => {
                    setMaxlenght(e)
                    setParams(()=>{params.maxlenght=e
                      return params
                    })
                  }}
                  // placeholder="请输入新密码"
                  min={minlenght}
                />

              </div>元
            </div>
            <Button type="primary" style={{ position: 'absolute', width: '100px', backgroundColor: '#4095E5', bottom: '22px', right: '160px' }} onClick={() => {resetDate() }}>
            重置
          </Button> 
          </div>
          <div style={{ alignItems: 'center', display: 'flex', width: '100%' }}>
            <div style={{ display: 'flex', marginTop: '10px' }}>
              <span
                style={{ height: '30px', lineHeight: '33px', color: '#4095E5' }}
              >
                商品关键字：
              </span>
              <div style={{ width: '240px', height: '40px', marginRight: '30px' }}>
                <Input
                  // value={this.state.keyCode}
                  value={keyCode}
                  onChange={(e) => {
                    setParams((params)=>{params.keyCode=e.target.value
                      return params
                    })
                    setkeyCode(e.target.value)
                  }}
                  placeholder="请输入关键字"
                />
              </div>
            </div>
            <div style={{ display: 'flex' }}>
              <span
                style={{ height: '30px', lineHeight: '33px', color: '#4095E5', marginLeft: '15px' }}
              >
                可否小刀：
              </span>
              <div style={{ width: '300px', height: '40px' }}>
                <Select
                  allowClear
                  value={knife}
                  style={{
                    width: 240,
                  }}
                  onChange={handleChange}
                >
                  <Option value={1}>可小刀</Option>
                  <Option value={0}>不议价</Option>
                  <Option value={2}>价格再议</Option>
                </Select>
              </div>
            </div>
          </div>
          <Button type="primary" style={{ position: 'absolute', width: '100px', backgroundColor: '#4095E5', bottom: '22px', right: '33px' }} onClick={() => {getFilter() }}>
            筛选
          </Button>
                

        </div>
         :
        <div className='operateBox'>
          <span  className={buttonColor==2?'buttonRightBlue':'buttonRight' }
            onClick={() => { setButtonColor(2); setIsShow(false);setHistorylist(0); getGoodsDate()}}
          >广场</span>
          <span className={buttonColor==3?'buttonRight1Blue':'buttonRight1' }
            onClick={() => {setButtonColor(3); setIsShow(true);setHistorylist(0); getChangingDate()}}
          >交易中
          <div className='circleStyle'>{number}</div>
          </span>
          <span className={buttonColor==1?'buttonYellowBlue':'buttonYellow'  }
            onClick={() => {setButtonColor(1); setIsShow(false);setHistorylist(1);getHistoryList()}}
          >交易记录</span>
          <span className='buttonRight' 
            onClick={() => { setVisible(true)}}
          >我要发布</span>
         { !isShow?<div className='addScreenBox' onClick={()=>setChangeValue(true)}>
            <span style={{ height: '30px', color: '#40a9ff', width: '90px', lineHeight: '30px' }}>添加筛选条件 </span>
            <DoubleRightOutlined style={{ color: '#40a9ff', marginRight: 20,marginTop:8 }} rotate={90} />
          </div>:''}
        </div>
        }
      </div>
      <Drawer
        title="发布商品"
        width={477}
        onClose={onClose}
        visible={visible}
        bodyStyle={{
          paddingBottom: 80,
        }}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={postGoodsDate}>
              发布
            </Button>
          </Space>
        }
      >
        <Form form={form} {...layout} hideRequiredMark>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                label="商品名"
                name="Name"
                rules={[
                  {
                    required: true,
                    message: '请输入商品名',
                  },
                ]}
              >
                <Input placeholder="请输入商品名" />
              </Form.Item>
            </Col></Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                label="商品描述"
                name="goodDetail"
                rules={[
                  {
                    required: true,
                    message: '请输入商品描述',
                  },
                ]}
              >
                <Input.TextArea rows={4} placeholder="请输入商品描述" />
              </Form.Item>
            </Col>


          </Row>
          
          <Row gutter={24}>
          <Col span={24}>
              <Form.Item
                label="原价"
                name="originalPrice"
                rules={[
                  {
                    required: true,
                    message: '请输入原价',
                  },
                ]}
              >
                <InputNumber
                  type="number"
                  addonAfter="元"
                //  value={maxlenght}
                  onChange={(e) => {
                    form.setFieldsValue({
                      originalPrice:e
                    })
                 }}
                // placeholder="请输入新密码"

                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="售价"
                name="price"
                rules={[
                  {
                    required: true,
                    message: '请输入售价',
                  },
                ]}
              >
                <InputNumber
                  type="number"
                  addonAfter="元"
                //  value={maxlenght}
                  onChange={(e) => {
                    form.setFieldsValue({
                      price:e
                    })
                 }}
                // placeholder="请输入新密码"

                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="还价"
                name="bigDeal"
                rules={[
                  {
                    required: true,
                    message: '请选择可否优惠',
                  },
                ]}
              >
                <Select defaultValue={0} placeholder="请选择校区">
                  <Option value={0}>不议价</Option>
                  <Option value={1}>可小刀</Option>
                  <Option value={2}>价格再议</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="商品图片"
                name="Url"
              // rules={[
              //   {
              //     required: true,
              //     message: 'Please enter url',
              //   },
              // ]}
              >
                <>
                <Consumer>
                  {value=>{return (<Upload
                    action="https://www.donglongdong.xyz/fileUpload"
                    data={{useMethod:'二手转让--上传商品图片',studentId:value?.studentInfo?.studentId}}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChangephoto}
                  >
                    {fileList.length >= 3 ? null : uploadButton}
                  </Upload>)}}
                  </Consumer>
                  <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                    <img
                      alt="example"
                      style={{
                        width: '100%',
                      }}
                      src={previewImage}
                    />
                  </Modal>
                </>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>

            <Col span={24}>
              <Form.Item
                name="owner"
                label="展示主图"
                rules={[
                  {
                    required: true,
                    message: 'Please select an owner',
                  },
                ]}
              >
                <>
                <Consumer>
                  {value=>{return <Upload
                   action="https://www.donglongdong.xyz/fileUpload"
                   data={{useMethod:'二手转让--上传商品主图',studentId:value?.studentInfo?.studentId}}
                    listType="picture-card"
                    fileList={mainfileList}
                    onPreview={handlePreview}
                    onChange={handleChangemainphoto}
                  >
                    {mainfileList.length >= 1 ? null : uploadButton}
                  </Upload>}}
                  </Consumer>
                </>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="anonymous"
                label="匿名发布"
              // rules={[
              //   {
              //     required: true,
              //     message: 'Please choose the approver',
              //   },
              // ]}
              >
                <Checkbox onChange={(e)=>{
                  if(e.target.checked)
                  {
                   form.setFieldsValue({anonymous:1})
                  }
                  else
                  {
                    form.setFieldsValue({anonymous:0}) 
                  }
                  
                }}/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="campus"
                label="校区"
                rules={[
                  {
                    required: true,
                    message: '请选择校区',
                  },
                ]}
              >
                <Select placeholder="请选择校区">
                  {schoolSect?.map((item, index) => {
                    return <Option value={item.campusName}>{item.campusName}</Option>
                  })

                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>

        </Form>
      </Drawer>
      {/* 广场 交易中 */}
        {historylist==0?<>   <div className='BigContent' onClick={()=>setChangeValue(false)}>
      
        <div style={{textAlign:'left',width:'100%',fontSize:'18px'}}>
          为您找到<span style={{color:'red',fontSize:22}}>{` ${total} `}</span>条商品
        </div>
         {
        goodsList?.map((item,index)=>{
          // debugger
          return <CommodityCard info={item} key={item.goodId} itemData={(e)=>{setitemData(e)}} openModal={(e)=>setDetailModalVisible(e)}/>
             
        })
      }
      </div>
      <Pagination style={{position:'absolute',bottom:'40px',right:'60px'}} pageSize={10} pageNum={current}  onChange={(e)=>onChangePage(e)} total={total} />
      </>:''}
      {/* 交易记录 */}
      {historylist==1?<>   <div className='BigContent' onClick={()=>setChangeValue(false)}>
      <div className='tableStyle'>
         <Table dataSource={DataSourceTable} columns={columns} />
      </div>
    
    </div>
    {/* <Pagination style={{position:'absolute',bottom:'40px',right:'60px'}} pageSize={10} pageNum={current}  onChange={(e)=>onChangePage(e)} total={total} /> */}
    </>:''}
   
    </div>
    </>
  );
}
